<?php
use Base\AdminController;
use Illuminate\Support\Str;
use JetBrains\PhpStorm\NoReturn;

class ScheduleController extends AdminController
{
    protected string $table = 'schedules';

    protected string $model = "schedule";

    /**
     * 初始化
     */
    #[NoReturn] public function init(): void
    {
        $this->routeWhiteLst = ['schedule@getoptions','schedule@index','schedule@add','schedule@edit','schedule@getlst','schedule@del'];
        parent::init();
    }

    #[NoReturn] public function getOptionsAction(): void
    {
        $data = dict('urgency');
        $result = [];
        foreach ($data as $key=>$vo) {
            $result[] = [
                'value'=>(int)$vo,
                'label'=>$key
            ];
        }
        $this->apiSuccess($result,"获取成功",20000);
    }

    /**
     * 获取列表页数据
     * @return void
     */
    #[NoReturn] public function indexAction(): void
    {
        try {
            $sql = App::make($this->getModelMame())
                ->join('users','schedules.user_id','=','users.id')
                ->select('schedules.*','users.avatar','users.nickname')
                ->when($this->includes,function ($query,$value) {
                    $query->with($value);
                })->when($this->where,function ($query,$value){
                    $query->where($value);
                })
                ->when($this->whereIn,function ($query,$value){
                    foreach ($value as $item) {
                        $query->whereIn($item[0], $item[1]);
                    }
                });
            if (Request::input("time")) {
                if (is_array(Request::input("time"))) {
                    $sql->whereBetween("created_at",Request::input("time"));
                }else {
                    $sql->whereDate("created_at",Request::input("time"));
                }
            }
            $sql->orderBy("id","desc");
            $org_id = $this->scopeOrg();
            if ($org_id) {
                $sql->whereIn("schedules.org_id", $org_id);
            }
            $data = $sql->paginate(Request::input("limit",1000),['*'],NULL,Request::input("p",1));
            $_data = collect($data->items())->toArray();
            foreach ($_data as $key=>$vo) {
                if ($vo['is_public']==0&&$vo['user_id']!=$this->member_id) {
                    unset($_data[$key]);
                    continue;
                }
                if ($vo['start_time'] && $vo['end_time']) {
                    if ((int)date("d",strtotime($vo['end_time']))!=(int)date("d",strtotime($vo['start_time']))) {
                        $_data[$key]['is_range'] = 1;
                        $_data[$key]['allDay'] = false;
                    }else {
                        $_data[$key]['is_range'] = 0;
                        $_data[$key]['allDay'] = true;
                    }
                }else {
                    $_data[$key]['is_range'] = 0;
                    $_data[$key]['allDay'] = true;
                }
                if ($vo['user_id'] == $this->member_id) {
                    $_data[$key]['is_owner']  = 1;
                }else {
                    $_data[$key]['is_owner']  = 0;
                }
            }
            $result = [
                'items' => array_values($_data),
                'total'=>$data->total(),
                'per_page' => $data->perPage(),
                'page' => $data->currentPage()
            ];
            $this->apiSuccess($result,"获取成功",20000);
        }catch (Exception $e) {
            $this->apiError($e->getMessage());
        }
    }

    #[NoReturn] public function getLstAction(): void
    {
        try {
            $sql = App::make($this->getModelMame())
                ->join('users','schedules.user_id','=','users.id')
                ->select('schedules.*','users.avatar','users.nickname')
                ->when($this->includes,function ($query,$value) {
                    $query->with($value);
                })->when($this->where,function ($query,$value){
                    $query->where($value);
                });
            $sql->orderBy("id","desc");
            $data = $sql->get()->toArray();
            foreach ($data as $key=>$vo) {
                if ($vo['is_public']==0&&$vo['user_id']!=$this->member_id) {
                    unset($data[$key]);
                    continue;
                }
                if ($vo['user_id'] == $this->member_id) {
                    $data[$key]['is_owner']  = 1;
                }else {
                    $data[$key]['is_owner']  = 0;
                }
                if ($vo['start_time'] && $vo['end_time']) {
                    if ((int)date("d",strtotime($vo['end_time']))!=(int)date("d",strtotime($vo['start_time']))) {
                        $allDay = false;
                    }else {
                        $allDay = true;
                    }
                }else {
                    $allDay = true;
                }
                $color = $vo['is_handle'] == 0 ? 'red' : 'green';
                $handel = $vo['is_handle'] == 0 ? '未开始' : '已完成';
                $day = $allDay ? '全天' : date("H:i",strtotime($vo['start_time']));
                $html = '
<div style="width: 300px;background: #336df2d9;display: flex;align-items: center;justify-content: left;padding: 10px;">
                    <img src="'.$vo['avatar'].'" style="width: 48px;height: 48px;border-radius: 48px;display: inline-block;border: 0;">
                    <span style="color: var(--el-color-white); margin-left: 5px" >
                      '.$vo['nickname'].'
                    </span>
                  </div>
                  <div style="border-left: 5px solid '.$color.'; padding: 5px; margin-top: 10px;">
                    '.$handel.'<span style="float: right; font-weight: 500">'.$day.'</span>
                  </div>
                  <p style="font-weight: 500">'.$vo['title']. '</p>
                  <p
                    class="demo-rich-content__desc"
                    style="color: var(--el-color-info);margin: 0 0 10px;"
                  >
                   ' .$vo['remark'].'
                  </p>';
                $data[$key]['html'] = $html;
            }
            $this->apiSuccess($data,"获取成功",20000);
        }catch (Exception $e) {
            $this->apiError($e->getMessage());
        }
    }

    /**
     * 显示
     * @return void
     */
    #[NoReturn] protected function operate(): void
    {
        try {
            $info = App::make($this->getModelMame())->where('id', Request::input("ids"))->first();
            if (!$info) $this->apiError("数据不存在");
            $info = $info->toArray();
            $info['time'] = [
                $info['start_time'],
                $info['end_time']
            ];
            $this->apiSuccess($info,"获取成功",20000);
        }catch (Exception $e) {
            $this->apiError($e->getMessage());
        }

    }

    /**
     * 修改
     * @return void
     */
    protected function update(): void
    {
        DB::beginTransaction();
        try {
            $params  = Request::all();
            $this->cleanCache();
//            $params['start_time'] = $params['time'][0];
//            $params['end_time'] = $params['time'][1];
            unset($params['time']);
            if (Request::input("id") !== null) {
                App::make($this->getModelMame())->where("id",Request::input("id"))->update($params);
                DB::commit();
                $this->apiSuccess([],"更新成功",20000);
            }else {
                $params['uuid'] = (string)Str::uuid();
                $params['created_at'] = date("Y-m-d H:i:s");
                if (DB::schema()->hasColumn($this->table, "org_id")) {
                    $params['org_id'] = $this->org['id'];
                }
                if (DB::schema()->hasColumn($this->table, "user_id")) {
                    $params['user_id'] = $this->member_id;
                }
                $res =  App::make($this->getModelMame())->insertGetId($params);
                //将任务添加至待办
                if (Request::input("category_type")==2) {
                    DoTaskModel::insert([
                        'uuid' => (string)Str::uuid(),
                        'type' => 2,
                        'user_id' => $this->member_id,
                        'review_user_id'=>$this->member_id,
                        'org_id' => $this->org['id'],
                        'title' => $params['title'],
                        'created_at' => date("Y-m-d H:i:s"),
                        'urgency'=>$params['type'],
                        'data' => json_encode($params),
                        'end_time'=>$params['end_time'],
                        'resource_id'=>$res
                    ]);
                }
                $info =  App::make($this->getModelMame())->where('id',$res)->first();
                DB::commit();
                $this->apiSuccess( $info->toArray(),"新增成功",20000);
            }
        } catch (Exception $exception) {
            DB::rollBack();
            Log::$customFileName = LOG_PATH."/errors/";
            Log::error($exception->getMessage().$exception->getTraceAsString());
            $this->apiError($exception->getMessage());
        }
    }
}
